//
//  AppDelegate.swift
//  MyWeibo
//
//  Created by cat on 15/7/27.
//  Copyright © 2015年 cat. All rights reserved.
//

import UIKit

/// 通知名
let XBXRootViewControllerSwitchNotification = "XBXRootViewControllerSwitchNotification"


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        // 注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchViewController:", name: XBXRootViewControllerSwitchNotification, object: nil)
        
        setupAppearance()
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        
        window?.backgroundColor = UIColor.whiteColor()
        
        window?.rootViewController = defaultViewController()
        
        window?.makeKeyAndVisible()
        
        
        return true
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func switchViewController(n: NSNotification) {
        let mainVC = n.object as! Bool
        
        window?.rootViewController = mainVC ? MainViewController() : WelcomeViewController()
    }
    // 返回默认登陆器
    private func defaultViewController() -> UIViewController {
        // 1.判断用户是否登录,
        if !UserAccount.userLogon {
            return MainViewController()
        }
        // 2.判断版本是否更新
        return isNewUpdate() ? NewFeatureViewController() : WelcomeViewController()
    }
    
    /// 检查是否有新版本
    private func isNewUpdate() -> Bool {
        // 1.获取程序当前的版本
        let currentVersion = Double(NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String)!
        
        // 2.获取程序之前的版本
        let sandboxVersionKey = "sandboxVersionKey"
        let sandboxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(sandboxVersionKey)
        
        // 3.当前版本保存到偏好设置中
        NSUserDefaults.standardUserDefaults().setDouble(currentVersion, forKey: sandboxVersionKey)
        
        NSUserDefaults.standardUserDefaults().synchronize()
        
        // 4.返回比较结果
        return currentVersion > sandboxVersion
    }
    

    func setupAppearance() {
        
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
        
    }
    
    
    


}

